const { Sequelize , DataTypes} = require('sequelize')
const {database,username,password,host} = require('../config')
const sequelize = new Sequelize(database, username,password, {
    host,
    dialect: 'mysql',
  });

const connectDb =async function(){
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');
      } catch (error) {
        console.error('Unable to connect to the database:', error);
      }
}

// 状态记录
const Record= sequelize.define('record',{
    id:{
        type:DataTypes.INTEGER,
        primaryKey:true,
        autoIncrement:true,
        comment:'id'
    },
    temperature:{
        type:DataTypes.STRING,
        comment:'温度'  
      },
    humidity:{
        type:DataTypes.STRING,
        comment:'湿度',
    },
    windSpeed:{
        type:DataTypes.STRING,
        comment:'风速',
    },
    light:{
        type:DataTypes.STRING,
        comment:'光照',
    },
    nitrogen:{
        type:DataTypes.STRING,
        comment:'氮含量',
    },
    switch:{
        type:DataTypes.STRING,
        comment:'开关',
        defaultValue: '0'
    }
})

// 操作记录表
const Log = sequelize.define('log',{
    id:{
        type:DataTypes.INTEGER,
        autoIncrement:true,
        primaryKey:true,
    },
    desc:{
        type:DataTypes.STRING,
    }
})

// 用户表
const User = sequelize.define('user',{
    id:{
      type:DataTypes.INTEGER,
      require:true,
      primaryKey:true,
      autoIncrement:true
    },
    username: {
        type:DataTypes.STRING,
        require: true
    },
    password: {
        type:DataTypes.STRING,
        require:true
    }
})
const init = async ()=>{
    await sequelize.sync({ force: true });
}

connectDb()
const DB ={
    Record,
    Log,
    init,
    User
}
module.exports ={
    sequelize,
    DB,
}